package com.studyyoun.android.nonghe.push.sql;
/**
 * Created by zhaolong on 2017/9/29.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.studyyoun.android.nonghe.push.JPushReceiverModel;
import com.studyyoun.android.nonghe.sql.CommonSqlBaseDao;
import com.studyyoun.android.nonghe.sql.SqlDBHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

/**
 * class infation
 */
public class PushReceiverSqlDBHelper extends CommonSqlBaseDao {

    private SQLiteDatabase mLiteDatabase;

    /**
     * CountDownLatch是JAVA提供在java.util.concurrent包下的一个辅助类，可以把它看成是一个计数器，其内部维护着一个count计数，只不过对这个计数器的操作都是原子操作，同时只能有一个线程去操作这个计数器，CountDownLatch通过构造函数传入一个初始计数值，调用者可以通过调用CounDownLatch对象的cutDown()方法，来使计数减1；
     * 如果调用对象上的await()方法，那么调用者就会一直阻塞在这里，直到别人通过cutDown方法，将计数减到0，才可以继续执行
     */
    //指定了计数的次数
    private static CountDownLatch latch =
            new CountDownLatch(1);
    private static Semaphore lock =
            new Semaphore(1, true);


    public PushReceiverSqlDBHelper(Context context) {
        super(context);
        latch.countDown();
    }

    public void insertPushMsgList(List<JPushReceiverModel> jPushReceiverModels) {

        try {
            if (latch.getCount() == 0 || mLiteDatabase == null) {
                mLiteDatabase = mSqlDBHelper.getWritableDatabase();
            }
            latch.await();
            lock.acquire();


            // 开始
            mLiteDatabase.beginTransaction();

            // 循环一万次
            for (JPushReceiverModel jPushReceiverModel : jPushReceiverModels) {
                insertOrUpdateArtModelFunction(jPushReceiverModel);
            }


            // 成功
            mLiteDatabase.setTransactionSuccessful();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            mLiteDatabase.endTransaction();
            lock.release();

            if (latch.getCount() == 1) {
                mLiteDatabase.close();
                mLiteDatabase = null;
            }

            latch.countDown();
        }


    }

    private void insertOrUpdateArtModelFunction(JPushReceiverModel artModel) {
        boolean isInsertNew;
        String querySql = "select * from " + SqlDBHelper.TABLE_NAME_JPUSH + " where msg_id=" + artModel.msgId;


        Cursor cursor = mLiteDatabase.rawQuery(querySql, null);

        if (cursor == null || cursor.getCount() == 0) {
            isInsertNew = true;
        } else {
            isInsertNew = false;
        }


        if (cursor != null) {
            cursor.close();
        }

        ContentValues classValues = new ContentValues();
        classValues.put("type_id", artModel.id);
        classValues.put("type", artModel.type);
        classValues.put("title", artModel.msgTitle);
        classValues.put("content", artModel.msgContent);
        classValues.put("msg_id", artModel.msgId);

        if (isInsertNew) {
            mLiteDatabase.insert(SqlDBHelper.TABLE_NAME_JPUSH, null, classValues);
        } else {
            mLiteDatabase.update(SqlDBHelper.TABLE_NAME_JPUSH, classValues, "msg_id=? ", new String[]{String.valueOf(artModel.msgId)});
        }
    }


    /**
     * 清除数据库中的数据
     */
    public void clearArtDb() {
        try {
            if (latch.getCount() == 0 || mLiteDatabase == null) {
                mLiteDatabase = mSqlDBHelper.getWritableDatabase();
            }
            latch.await();
            lock.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String clearsQL = "delete from  " + SqlDBHelper.TABLE_NAME_JPUSH;

        mLiteDatabase.execSQL(clearsQL);

        lock.release();

        if (latch.getCount() == 1) {
            mLiteDatabase.close();
            mLiteDatabase = null;
        }

        latch.countDown();
    }

    public void insertArt(JPushReceiverModel artModel) {
        try {
            if (latch.getCount() == 0 || mLiteDatabase == null) {
                mLiteDatabase = mSqlDBHelper.getWritableDatabase();
            }
            latch.await();
            lock.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        insertOrUpdateArtModelFunction(artModel);

        lock.release();

        if (latch.getCount() == 1) {
            mLiteDatabase.close();
            mLiteDatabase = null;
        }

        latch.countDown();
    }


    public List<JPushReceiverModel> queryAllMsgModelList() {
        try {
            if (latch.getCount() == 0 || mLiteDatabase == null) {
                mLiteDatabase = mSqlDBHelper.getReadableDatabase();
            }
            latch.await();
            lock.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<JPushReceiverModel> list = new ArrayList<>();


        String sql = "select * from " + SqlDBHelper.TABLE_NAME_JPUSH;

        Cursor cursor = mLiteDatabase.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                JPushReceiverModel artModel = new JPushReceiverModel();


                artModel.id = cursor.getInt(cursor.getColumnIndex("type_id"));
                artModel.type = cursor.getString(cursor.getColumnIndex("type"));
                artModel.msgTitle = cursor.getString(cursor.getColumnIndex("title"));

                artModel.msgContent = cursor.getString(cursor.getColumnIndex("content"));
                artModel.msgId = cursor.getString(cursor.getColumnIndex("msg_id"));

                list.add(artModel);
            }
        }
        lock.release();

        if (latch.getCount() == 1) {
            mLiteDatabase.close();
            mLiteDatabase = null;
        }

        latch.countDown();

        return list;
    }

}
